/*
 * @Description: 异步并行钩子
 * @Author: wangqi
 * @Date: 2021-04-17 12:05:11
 * @LastEditTime: 2021-04-18 11:21:05
 */

// 异步并行的钩子
// 所有tapAsync 注册的异步函数, 都会在callAsync函数前执行; callAsync是最后执行的
class AsyncParallelHook {
    constructor(args) {
        this.hooks = [];
    }

    tapAsync(name, task) {
        this.hooks.push(task);
    }

    callAsync(...res) {
        let index = 0;
        let finalCallback = res.pop();
        let done = () => {
            index++;
            if (index == this.hooks.length) finalCallback();
        }
        // 体现并行处理和串行的区别
        this.hooks.forEach((hook) => {
            hook(...res, done);
        });
    }

}

let asyncparallelhook = new AsyncParallelHook(['name', 'cb']);
asyncparallelhook.tapAsync('node', (name, cb) => {
    setTimeout(() => {
        console.log('node', name, cb);
        cb();
    }, 1000);
});

asyncparallelhook.tapAsync('vue', (name, cb) => {
    setTimeout(() => {
        console.log('vue', name, cb)
        cb();
    }, 2000);
});

asyncparallelhook.callAsync('wq', function () {
    console.log("end")
});


